package com.wms_backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.wms_backend.entity.Result;
import com.wms_backend.security.UserDetailsImpl;
import com.wms_backend.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Objects;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/add-company")
    public Result addCompany(@RequestBody JSONObject param) {
        UserDetailsImpl principal = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<? extends GrantedAuthority> roles = principal.getAuthorities();
        GrantedAuthority desiredAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
        boolean isAdmin = false;
        for (GrantedAuthority role : roles) {
            if (role.equals(desiredAuthority)) {
                isAdmin = true;
            }
        }
        if (!isAdmin) {
            return Result.error("未拥有足够的权限");
        }
        return adminService.addCompany(param);
    }

}
